﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Collections;
using System.Xml;
/// <summary>
/// xwd：2012-10-12
/// </summary>
namespace WeChatLibrary.CheckSignUtility
{
    public static class WeChatClassUtility
    {
        /// <summary>   
        /// 验证签名   
        /// </summary>   
        /// <param name="signature"></param>   
        /// <param name="timestamp"></param>   
        /// <param name="nonce"></param>   
        /// <returns></returns>   
        public static bool CheckSignature(this String token, String signature, String timestamp, String nonce)
        {
            String[] arr = new String[] { token, timestamp, nonce };
            // 将token、timestamp、nonce三个参数进行字典序排序     
            Array.Sort<String>(arr);

            StringBuilder content = new StringBuilder();
            for (int i = 0; i < arr.Length; i++)
            {
                content.Append(arr[i]);
            }

            String tmpStr = SHA1_Encrypt(content.ToString());

            // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信     
            return tmpStr != null ? tmpStr.Equals(signature) : false;
        }
        /// <summary>
        /// 使用缺省密钥给字符串加密
        /// </summary>
        /// <param name="Source_String"></param>   
        /// <returns></returns>   
        private static string SHA1_Encrypt(string Source_String)
        {
            byte[] StrRes = Encoding.Default.GetBytes(Source_String);
            HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
            StrRes = iSHA.ComputeHash(StrRes);
            StringBuilder EnText = new StringBuilder();
            foreach (byte iByte in StrRes)
            {
                EnText.AppendFormat("{0:x2}", iByte);
            }
            return EnText.ToString();
        }

        /// <summary>
        /// 将xml文件转换成Hashtable
        /// </summary>
        /// <param name="xml">要转换的xml字符串</param>
        /// <returns></returns>
        public static Hashtable ParseXmlToHashtable(this String xml)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
            XmlNode bodyNode = xmlDocument.ChildNodes[0];
            Hashtable ht = new Hashtable();
            if (bodyNode.ChildNodes.Count > 0)
            {
                foreach (XmlNode xn in bodyNode.ChildNodes)
                {
                    ht.Add(xn.Name, xn.InnerText);
                }
            }
            return ht;
        }

        /// <summary>
        /// 将字符转换成CDATA数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string ParseCDATA(this String data)
        {
            return "<![CDATA[" + data + "]]>";
        }
    }
}
